import React from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import TodoApp from './TodoApp.js';
// const TodoApp = () => <div>Todo</div>
class User extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            username: this.props.username,
            password: '',
            error: null
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.requestBaseURL = this.props.requestBaseURL;
    }
    handleChange(event) {
        this.setState({[event.target.name]: event.target.value});
    }
	hasError(result){
        if(result.code < 0)
            return result.msg;		
        return null;
    }    
    handleSubmit(event) {
        // data validation
        if(event.target.name === 'logout'){
            fetch(this.requestBaseURL + 'logout', {method: 'GET', 
                credentials: 'include'
            })
            .then(res => res.json())
            .then(
            (result) => {
                let error = this.hasError(result);
                if(error){
                    this.setState({
                    error: error
                    });
                }
                else{
                    this.props.updateLogin();
                }
            },
            (error) => {
                this.setState({error: error.message});
            }
            )
        }
        else{
            let submitStr = `username=${this.state.username}&password=${this.state.password}`;
            event.preventDefault(); // use ajax, preventDefault behaviour 
            fetch(this.requestBaseURL + 'login', {method: 'POST', 
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: submitStr,
                credentials: 'include'
            })
            .then(res => res.json())
            .then(
            (result) => {
                let error = this.hasError(result);
                if(error){
                    this.setState({
                    error: error
                    });
                }
                else{
                    this.props.updateLogin(this.state.username);
                }
            },
            (error) => {
                this.setState({error: error.message});
            }
            )
        }		

    }
    render(){
		let error = null;
		if(this.state.error){
			error = <div> Error: {this.state.error}</div>
        }
        if(this.props.isLogin){
            return(
                <div>
                    <div> Welcome, {this.state.username}</div>
                    <button onClick={this.handleSubmit} name="logout">Logout</button>
                </div>
            )
        }
        else{
            return(
                <form onSubmit={this.handleSubmit} name="login">
                    {error}
                    <label >username</label>
                    <input type="text" name="username" 
                    value={this.state.username}
                    onChange={this.handleChange}
                    />
                    <label> password</label>
                    <input type="password" name="password" 
                    value={this.state.password}
                    onChange={this.handleChange}
                    />
                    <input type="submit" value="login"></input>
                </form>  
                );    
        }
    }
}


export default class App extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            isLogin: false,
            username: ''
        };
        this.updateLogin = this.updateLogin.bind(this);
    }
    updateLogin(username){
        this.setState({
            isLogin: !this.state.isLogin,
            username: username
        });
    }
    makeLogin(){
        this.setState({isLogin: true})
    }
    render() {
        let requestBaseURL = this.props.requestBaseURL;
        let isLogin = this.state.isLogin;
        let userName = this.state.username;
        return(
        <Router>
            <div className="todoapp">
            <nav>
                <ul className="filters">
                <li>
                    <Link to="/">Home</Link>
                </li>
                <li>
                    <Link to="/users/">Users</Link>
                </li>
                </ul>
            </nav>

            <Route path="/" exact render={props =>
                <TodoApp {...props}
                requestBaseURL = {requestBaseURL}                
                makeLogin = {() => this.makeLogin()}
                isLogin = {isLogin}
                />} />
            <Route path="/users/" render={
                props => 
                <User {...props} 
                requestBaseURL = {requestBaseURL}
                isLogin ={isLogin}
                updateLogin = {this.updateLogin}
                username = {userName}
                />                
            }/>
            </div>
        </Router>
        );
    }
}